﻿using System;
using System.Linq;
using Medianamik.Core;
using Medianamik.Core.Security;
using Medianamik.UI;
using Medianamik.Core.Sugar;

namespace Thermostat.Shop.Views
{
    public partial class GroupSelector : BasePage
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!Page.IsPostBack)
            {
                var groups = MedianamikUser.Groups
                     .GetAllAllowedGroups(MedianamikUserProfile)
                     .Select(g => new { g.TranslatedName, g.Name }).ToList();

                var groupsToExcludeParam = Request.QueryString.GetValue<string>(DefaultParamNames.GroupsToExclude) ?? "";

                if (groupsToExcludeParam.Length > 0)
                {
                    var decoded = groupsToExcludeParam.DecodeBase64();
                    var groupsToExclude = decoded.Split(',');

                    groupsToExclude.ForEach(groupToRemove =>
                        groups.RemoveAll(g => g.Name.EqualsIgnoreCase(groupToRemove)));
                }

                //.Distinct() is a dirty patch... ya should fix it cleanly later
                GroupList.DataSource = groups.OrderBy(x => x.TranslatedName).Distinct();
                GroupList.DataBind();
                GroupList.Items.Insert(0, "");
            }
        }
    }
}
